from __future__ import(absolute_import, division, print_function, unicode_literals)
from datetime import datetime, timedelta
import backtrader as bt
from backtrader import cerebro
import time
# 推荐10款国内外数字货币行情API
# https://zhuanlan.zhihu.com/p/130263816
# 5个主流的数字货币实时价格API
# https://blog.csdn.net/shebao3333/article/details/100977486
def connect_broker():
    api_key = "217078fb-bb7e-47a6-be2d-10c81b22a645"
    secret_key = "571543CA73D1970C5A81380D93D9AB0A"
    passphrase = "guavaguava"
    config = {'urls': {'api': 'https://www.okex.win'},
                         'apiKey': api_key,
                         'secret': secret_key,
                         'nonce': passphrase
                        }
    broker = bt.brokers.CCXTBroker(exchange='okex',
                                   currency='USD', config=config)
    cerebro.setbroker(broker)

    # Create data feeds
    data_ticks = bt.feeds.CCXT(exchange='okex', symbol='ETH-USDT-SWAP',
                              name="ETH-USDT-SWAP",
                              timeframe=bt.TimeFrame.Ticks,
                              compression=1, config=config)
    cerebro.adddata(data_ticks)


class TestStrategy(bt.Strategy):
    def next(self):
        print('*' * 5, 'NEXT:', bt.num2date(self.data.datetime[0]), self.data._name, self.data.open[0], self.data.high[0],
              self.data.low[0], self.data.close[0], self.data.volume[0],
              bt.TimeFrame.getname(self.data._timeframe), len(self.data))

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    api_key = "217078fb-bb7e-47a6-be2d-10c81b22a645"
    secret_key = "571543CA73D1970C5A81380D93D9AB0A"
    passphrase = "guavaguava"
    config = {'urls': {'api': {'rest':'https://www.okex.win'}},
              'hostname':'okex.win',
              'apiKey': api_key,
              'secret': secret_key,
              'nonce': passphrase
              }
    hist_start_date = datetime.utcnow() - timedelta(minutes=10)
    data_min = bt.feeds.CCXT(exchange='okex', symbol='ETH-USDT-SWAP',
                              name="ETH-USDT-SWAP",fromdate=hist_start_date,
                             timeframe=bt.TimeFrame.Minutes, config=config)
    cerebro.adddata(data_min)
    cerebro.addstrategy(TestStrategy)
    result = cerebro.run()
    strat = result[0]
    print('sharpe ratio:', strat.analyzers.SharpeRatio.get_analysis())
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    print('回撤指标:', strat.analyzers.DW.get_analysis())
    # cerebro.plot(style='bar')  # 显示回测结果

    cerebro.plot()  # 显示回测结果
